from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

# 在 accounts/utils.py 中

import time
import os
import subprocess
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import threading

class MyHandler(FileSystemEventHandler):
    def on_created(self, event):
        from accounts.models import Video
        if not event.is_directory:
            file_name = os.path.basename(event.src_path)
            # if file_name.endswith(('.mp4', '.avi', '.mkv')):
            file_path = os.path.join('videos/', file_name)
            Video.objects.create(name=file_name, path=file_path)  # 将文件信息添加到数据库
            print(f"文件已创建并添加到数据库: {file_name}")

    def on_deleted(self, event):
        from accounts.models import Video
        if not event.is_directory:
            file_name = os.path.basename(event.src_path)
            Video.objects.filter(name=file_name).delete()  # 从数据库中删除文件信息
            print(f"文件已删除并从数据库移除: {file_name}")
    

def start_watchdog(path):
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=False)

    observer.start()
    print(f"开始监控: {path}")

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()


def send_mail(to, template, context):
    html_content = render_to_string(f"accounts/emails/{template}.html", context)
    text_content = render_to_string(f"accounts/emails/{template}.txt", context)

    msg = EmailMultiAlternatives(
        context["subject"], text_content, settings.DEFAULT_FROM_EMAIL, [to]
    )
    msg.attach_alternative(html_content, "text/html")
    msg.send()


def send_activation_email(request, email, code):
    context = {
        "subject": _("Profile activation"),
        "uri": request.build_absolute_uri(
            reverse("accounts:activate", kwargs={"code": code})
        ),
    }

    send_mail(email, "activate_profile", context)


def send_activation_change_email(request, email, code):
    context = {
        "subject": _("Change email"),
        "uri": request.build_absolute_uri(
            reverse("accounts:change_email_activation", kwargs={"code": code})
        ),
    }

    send_mail(email, "change_email", context)


def send_reset_password_email(request, email, token, uid):
    context = {
        "subject": _("Restore password"),
        "uri": request.build_absolute_uri(
            reverse(
                "accounts:restore_password_confirm",
                kwargs={"uidb64": uid, "token": token},
            )
        ),
    }

    send_mail(email, "restore_password_email", context)


def send_forgotten_username_email(email, username):
    context = {
        "subject": _("Your username"),
        "username": username,
    }

    send_mail(email, "forgotten_username", context)
